#include <string>
#include <iostream>
using std::string;
#include "model.h"


Model::Model() :
  cur_ticks(0), prev_ticks(0), ticks(0),
  xmlParser(ParseXML::getInstance()),
  env( SDL_putenv(const_cast<char*>("SDL_VIDEO_CENTERED=center")) ),
  screenWidth(xmlParser->getXmlInt("screen_width")),
  screenHeight(xmlParser->getXmlInt("screen_height")),
  star_number(xmlParser->getXmlInt("star_number")),
  screen(SDL_SetVideoMode(screenWidth, screenHeight, 16, SDL_HWSURFACE)),
  bgSurface(SDL_LoadBMP(xmlParser->getXmlString("bg").c_str())),
  starSurface(SDL_LoadBMP(xmlParser->getXmlString("star").c_str())),
  starFrame(new Frame(starSurface, screen, xmlParser->getXmlInt("star_width"), xmlParser->getXmlInt("star_height"), 0, 0)),
  background(bgSurface, screen, screenWidth, screenHeight, 0, 0),
  stars(star_number,Sprite(0, 0, 0, 0, starFrame))
  {
    if (SDL_Init( SDL_INIT_VIDEO ) != 0) {
      throw string("Unable to initialize SDL: ");
    }
   srand((unsigned)time(0));
  for(int i = 0 ; i < star_number ; i++)
  {
	  
	  stars[i].setX(rand() % screenWidth );
	  stars[i].setY(rand() % screenHeight );
	  stars[i].setXSpeed(rand() % screenWidth - screenWidth/2);
	  stars[i].setYSpeed(rand() % screenHeight - screenHeight/2);
  }
  if (screen == NULL) { throw string("Unable to set video mode!"); }
  if (bgSurface == NULL) { throw string("No background surface!"); }
  if (starSurface == NULL) { throw string("No star surface!"); }
  Uint32 colorkey = SDL_MapRGB(starSurface->format, 255, 0, 255);
  SDL_SetColorKey(starSurface, SDL_SRCCOLORKEY|SDL_RLEACCEL, colorkey);
  cur_ticks = SDL_GetTicks();
}

Model::~Model() {
  delete starFrame;
  // Not supposed to free the surface returned by SDL_SetVideoMode
  //SDL_FreeSurface(screen);
  SDL_FreeSurface(bgSurface);
  SDL_FreeSurface(starSurface);
  xmlParser = NULL;
  
}

void Model::update() {
  prev_ticks = cur_ticks;
  cur_ticks = SDL_GetTicks();
  ticks = cur_ticks-prev_ticks;
  for(int i = 0 ; i < star_number ; i++)
  {
	  stars[i].update(ticks);
  }
}

void Model::draw() const {
  background.draw(0, 0);
  for(int i = 0 ; i < star_number ; i++)
  {
	  stars[i].draw();
  }
  SDL_Flip(screen);
}
